/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package chenxu.test.jms.storm;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichBolt;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Tuple;
/**
 * A generic <code>backtype.storm.topology.IRichBolt</code> implementation
 * for testing/debugging the Storm JMS Spout and example topologies.
 * <p/>
 * For debugging purposes, set the log level of the 
 * <code>backtype.storm.contrib.jms</code> package to DEBUG for debugging
 * output.
 * @author tgoetz
 *
 */
@SuppressWarnings("serial")
public class GenericHbaseBolt extends BaseRichBolt {
	private static final Logger LOG = LoggerFactory.getLogger(GenericHbaseBolt.class);
	private OutputCollector collector;
	private boolean autoAck = false;
	private boolean autoAnchor = false;
	private Fields declaredFields;
	private String name;
	private HTable table;
	
	/**
	 * Constructs a new <code>GenericBolt</code> instance.
	 * 
	 * @param name The name of the bolt (used in DEBUG logging)
	 * @param autoAck Whether or not this bolt should automatically acknowledge received tuples.
	 * @param autoAnchor Whether or not this bolt should automatically anchor to received tuples.
	 * @param declaredFields The fields this bolt declares as output.
	 */
	public GenericHbaseBolt(String name, boolean autoAck, boolean autoAnchor, Fields declaredFields){
		this.name = name;
		this.autoAck = autoAck;
		this.autoAnchor = autoAnchor;
		this.declaredFields = declaredFields;
	}
	
	public GenericHbaseBolt(String name, boolean autoAck, boolean autoAnchor){
		this(name, autoAck, autoAnchor, null);
	}

	@SuppressWarnings("rawtypes")
	public void prepare(Map stormConf, TopologyContext context,
			OutputCollector collector) {
		this.collector = collector;
		Configuration conf = new Configuration();
		conf.set("hbase.zookeeper.quorum", "bjtest1hadoop01,bjtest1hadoop02,bjtest1hadoop03");
		try {
			table = new HTable(conf , "test-storm");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	public void execute(Tuple input) {
//		LOG.debug("[" + this.name + "] Received message: " + input);
//		System.err.println("=========== Received message: " + input.getValues());

		List<Put> puts = new ArrayList<Put>();
		if(input.getValues().isEmpty())
			return;
		Put put = new Put(Bytes.toBytes((String)input.getValues().get(0)));
		for(int i=1; i<input.getValues().size(); i++) {
			put.add(Bytes.toBytes("f1"), Bytes.toBytes(i), Bytes.toBytes((String)input.getValues().get(i)));
			puts.add(put);
		}
		
		try {
			table.put(puts);
			table.flushCommits();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			puts.clear();
		}
		
		// only emit if we have declared fields.
		if(this.declaredFields != null){
			LOG.debug("[" + this.name + "] emitting: " + input);
			if(this.autoAnchor){
				this.collector.emit(input, input.getValues());
			} else{
				this.collector.emit(input.getValues());
			}
		}
		
		if(this.autoAck){
			LOG.debug("[" + this.name + "] ACKing tuple: " + input);
			this.collector.ack(input);
		}
		
	}

	public void cleanup() {
		try {
			table.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void declareOutputFields(OutputFieldsDeclarer declarer) {
		if(this.declaredFields != null){
			declarer.declare(this.declaredFields);
		}
	}
	
	public boolean isAutoAck(){
		return this.autoAck;
	}
	
	public void setAutoAck(boolean autoAck){
		this.autoAck = autoAck;
	}

}
